﻿using IdentityServer4.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using static IdentityModel.OidcConstants;

namespace ZhongJia.Lock.Web.Extensions.ExternalLogin
{
    public class TwitterGrant : IExtensionGrantValidator
    {
        public string GrantType
        {
            get
            {
                return "twitterAuth";
            }
        }

        public async Task ValidateAsync(ExtensionGrantValidationContext context)
        {
            var userToken = context.Request.Raw.Get("id_token");

            if (string.IsNullOrEmpty(userToken))
            {
                context.Result = new GrantValidationResult(TokenErrors.InvalidGrant, null);
                return;
            }

            HttpClient client = new HttpClient();
            client.SetBearerToken(userToken);
            var request = client.GetAsync("https://api.twitter.com/1.1/account/verify_credentials.json?include_email=true").Result;
            if (request.StatusCode == System.Net.HttpStatusCode.OK)
            {
                context.Result = new GrantValidationResult("0001", "google");
                return;
            }
            else
            {
                return;
            }
        }
    }
}
